//
//  VoiceChatViewController.m
//  RainbowFM
//
//  Created by Kratos on 14/12/14.
//  Copyright (c) 2014年 RB. All rights reserved.
//

#import "VoiceChatViewController.h"

#import "VoiceChatStatusView.h"
#import "VoiceChatContentsView.h"

/*
#import "AnyChatPlatform.h"
#import "AnyChatDefine.h"
#import "AnyChatErrorCode.h"
*/
#import "AnyChatModel.h"


@interface VoiceChatViewController ()/*<AnyChatNotifyMessageDelegate,AnyChatTextMsgDelegate>*/
@property (nonatomic , strong)  VoiceChatStatusView *statusview;
@property (nonatomic , strong)  VoiceChatContentsView *contentsview;

//@property (nonatomic , strong) AnyChatPlatform *anyChat;
@property (nonatomic , assign) BOOL theOnLineLoginState;
@property (nonatomic , strong) LiveChatModel *liveChatModel;
@property (nonatomic , strong) NSMutableArray *usersList;
@end

@implementation VoiceChatViewController

-(void)awakeFromNib
{
    _liveChatModel = [LiveChatModel new];
    _liveChatModel.serverIP = @"183.230.37.145";
    _liveChatModel.serverPort = 8906;
    _liveChatModel.myUserName = @"jianghe";
    _liveChatModel.roomNum = 1;

    _usersList = [NSMutableArray array];
    
}

/*
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _contentsview = _LoadXib(VoiceChatContentsView, nil, nil);
    _contentsview.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
    _contentsview.frame = self.view.bounds;
    [self.view addSubview:_contentsview];
    
    __weak typeof(self) self_ = self;
    _contentsview.takeOffBlock = ^(){
        [self_ onLogout];
        [AnyChatPlatform Release];
        [self_ navBackAction];
    };
    
    _statusview = _LoadXib(VoiceChatStatusView, nil, nil);
    _statusview.autoresizingMask = UIViewAutoresizingFlexibleTopMargin |UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
    _statusview.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 64.f);
    [self.view addSubview:_statusview];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AnyChatNotifyHandler:) name:@"ANYCHATNOTIFY" object:nil];
    
    [AnyChatPlatform InitSDK:0];
    
    _anyChat = [[AnyChatPlatform alloc] init];
    _anyChat.notifyMsgDelegate = self;
    _anyChat.textMsgDelegate = self;
    //登陆
    [self onLogin];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    
}


#pragma mark - AnyChatNotifyMessageDelegate

// 连接服务器消息
- (void) OnAnyChatConnect:(BOOL) bSuccess
{
    if (bSuccess)
    {
        
    }
}

// 用户登陆消息
- (void) OnAnyChatLogin:(int) dwUserId : (int) dwErrorCode
{
    
    if(dwErrorCode == GV_ERR_SUCCESS)
    {
        _liveChatModel.myUserID = dwUserId;
        [AnyChatPlatform EnterRoom:_liveChatModel.roomNum :@""];
    }
    else
    {
        _theOnLineLoginState = NO;
    }
    
}

// 用户进入房间消息
- (void) OnAnyChatEnterRoom:(int) dwRoomId : (int) dwErrorCode
{
    if (dwErrorCode != 0)
    {
        _theOnLineLoginState = NO;
        [self timeOutMsg];
    }
    else
    {
        _theOnLineLoginState = YES;
        [_statusview setStatus:VoiceChatStatusOnlining];
        [self StartVideoChat];
    }
    
}

// 房间在线用户消息
- (void) OnAnyChatOnlineUser:(int) dwUserNum : (int) dwRoomId
{
    [_usersList removeAllObjects];
    [_usersList addObjectsFromArray:[self getOnlineUserArray]];
}

// 用户进入房间消息
- (void) OnAnyChatUserEnterRoom:(int) dwUserId
{
    [_statusview setStatus:VoiceChatStatusWaiting];
    [_usersList removeAllObjects];
    [_usersList addObjectsFromArray:[self getOnlineUserArray]];
}

// 用户退出房间消息
- (void) OnAnyChatUserLeaveRoom:(int) dwUserId
{
    if (dwUserId == _liveChatModel.myUserID) {
        [self FinishVideoChat];
        _theOnLineLoginState = NO;
        [_statusview setStatus:VoiceChatStatusOutofline];
    }
}

// 网络断开消息
- (void) OnAnyChatLinkClose:(int) dwErrorCode
{
    [AnyChatPlatform LeaveRoom:-1];
    [AnyChatPlatform Logout];
    _theOnLineLoginState = NO;
    [_statusview setStatus:VoiceChatStatusOutofline];
}

- (NSMutableArray *) getOnlineUserArray
{
    NSMutableArray *onLineUserList = [[NSMutableArray alloc] initWithArray:[AnyChatPlatform GetOnlineUser]];
    [onLineUserList insertObject:_F(@"%i",_liveChatModel.myUserID) atIndex:0];
    return onLineUserList;
}

//文字信息回调
- (void) OnAnyChatTextMsgCallBack:(int) dwFromUserid : (int) dwToUserid : (BOOL) bSecret : (NSString*) lpMsgBuf
{
    //{"instruction":"100"} 退出1号播导房间， 进入2号主持人房间 {"instruction":"200"} 主持人请求视频连接
    BOOL hasError = NO;
    if (lpMsgBuf && lpMsgBuf.length > 0) {
        NSData *data = [lpMsgBuf dataUsingEncoding:NSUTF8StringEncoding];
        
        NSError *error;
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        if (!error && dataDic) {
            NSString *codn = dataDic[@"instruction"];
            if (codn && codn.length > 0) {
                switch ([codn integerValue]) {
                    case 100:
                    {
                        [AnyChatPlatform LeaveRoom:-1];
                        [AnyChatPlatform EnterRoom:2 :@""];
                        _liveChatModel.roomNum = 2;
                    }
                        break;
                    case 200:
                    {
                        if (_theOnLineLoginState == YES) {
                            // request other user video
                            [AnyChatPlatform UserSpeakControl: dwFromUserid:YES];
                            [AnyChatPlatform SetVideoPos:dwFromUserid: _contentsview.chatView:0:0:0:0];
                            [AnyChatPlatform UserCameraControl:dwFromUserid : YES];
                            
                            _liveChatModel.compereUserID = dwFromUserid;
                        }else{
                            hasError = YES;
                        }
                    }
                        break;
                    default:
                        hasError = YES;
                        break;
                }
            }else{
                hasError = YES;
            }
        }else
        {
            hasError = YES;
        }
    }else{
        hasError = YES;
    }
    
    if (hasError) {
        [AnyChatPlatform Logout];
    }
}

#pragma mark - Instance Method
- (void)AnyChatNotifyHandler:(NSNotification*)notify
{
    NSDictionary* dict = notify.userInfo;
    [_anyChat OnRecvAnyChatNotify:dict];
}

- (void) StartVideoChat
{
    //Get a camera, Must be in the real machine.
    NSMutableArray* cameraDeviceArray = [AnyChatPlatform EnumVideoCapture];
    if (cameraDeviceArray.count > 0)
    {
        [AnyChatPlatform SelectVideoCapture:[cameraDeviceArray objectAtIndex:1]];
    }
    
    // open local video
    [AnyChatPlatform SetSDKOptionInt:BRAC_SO_LOCALVIDEO_OVERLAY :1];
    [AnyChatPlatform UserSpeakControl: -1:YES];
    [AnyChatPlatform SetVideoPos:-1 :_contentsview :0 :0 :0 :0];
    [AnyChatPlatform UserCameraControl:-1 : YES];
    
    
    [AnyChatPlatform SetSDKOptionInt:BRAC_SO_LOCALVIDEO_ORIENTATION : self.interfaceOrientation];
}


- (void) FinishVideoChat
{
    // 关闭摄像头
    [AnyChatPlatform UserSpeakControl: -1 : NO];
    [AnyChatPlatform UserCameraControl: -1 : NO];
    
    //关闭主持人摄像头
    if (_liveChatModel.compereUserID > 0) {
        [AnyChatPlatform UserSpeakControl:_liveChatModel.compereUserID : NO];
        [AnyChatPlatform UserCameraControl:_liveChatModel.compereUserID : NO];
    }
    
    
    _liveChatModel.myUserID = -1;
    _liveChatModel.compereUserID = -1;
    
}


#pragma mark - chat
- (void)onLogin
{
    if (_theOnLineLoginState == NO)
    {
        [_statusview setStatus:VoiceChatStatusWaiting];
        [AnyChatPlatform Connect:_liveChatModel.serverIP : _liveChatModel.serverPort];
        [AnyChatPlatform Login:_liveChatModel.myUserName : @""];
    }
    
}

//推出登陆
- (void) onLogout
{
    if (_theOnLineLoginState == YES)
    {
        [AnyChatPlatform LeaveRoom:-1];
        [AnyChatPlatform Logout];
        _liveChatModel.myUserID = -1;
        _theOnLineLoginState = NO;
        [_statusview setStatus:VoiceChatStatusOutofline];
    }
}

//连接超时
- (void)onLoginLoadingAnimatedRunTime
{
    int theTimes = 0;
    while (_theOnLineLoginState == NO && theTimes < 6)
    {
        sleep(1);
        theTimes++;
        
        if (theTimes == 5 ) {
            [self timeOutMsg];
        }
    }
}

- (void) timeOutMsg
{
    if (_theOnLineLoginState == NO)
    {
        [_statusview setStatus:VoiceChatStatusTimeout];
    }
}

-(void)dealloc
{
    [AnyChatPlatform Release];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
*/
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
